import router from './index'
import store from '../store'
import { getToken } from '../utils/auth'

router.beforeEach((to, from, next) => {
  // 用户已登录且有用户名，禁止访问/login，跳转overview
  if (store.state.user.loginState && store.state.user.userInfo && store.state.user.userInfo.name) {
    if (to.path === '/login') {
      next({ name: 'overview' })
    } else {
      next()
    }
    return
  }
  // 有token但未登录，允许进入/login
  const token = getToken()
  if (token && (!store.state.user.userInfo || !store.state.user.userInfo.name)) {
    if (to.path === '/login') {
      next()
    } else {
      next()
    }
    return
  }
  // 白名单
  if (to.path === '/login' || to.path.startsWith('/customer')) {
    next()
  } else {
    next('/login')
  }
})